<template>
	<view>
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<view class="uni-group">
				<button class="uni-button" type="primary" size="mini" @click="OpenPP()"
					v-if="userInfo.username == 'admin'">新增</button>
			</view>
		</view>
		<view class="uni-container">
			<uni-table border stripe emptyText="暂无更多数据">
				<!-- 表头行 -->
				<uni-tr>
					<uni-th align="center">绑定账号</uni-th>
					<uni-th align="center">服务器名称</uni-th>
					<uni-th align="center">服务器类型</uni-th>
					<uni-th align="center">是否有效</uni-th>
					<uni-th align="center">有效期</uni-th>
					<uni-th align="left" v-if="userInfo.username == 'admin'">操作</uni-th>
				</uni-tr>
				<!-- 表格数据行 -->
				<uni-tr v-for="(item,key) in tableData">
					<uni-td>{{item.username}}</uni-td>
					<uni-td>{{item.name}}</uni-td>
					<uni-td>{{item.type}}</uni-td>
					<uni-td>
						<switch :checked="item.valid" color="#00aaff" style="transform:scale(0.7)"
							@change="setValid(item)" />
					</uni-td>
					<uni-td v-if="userInfo.username != 'admin'">{{item.end_date | timeOut(item.end_date)}}</uni-td>
					<uni-td v-if="userInfo.username == 'admin'">
						<uni-datetime-picker returnType="timestamp" v-model="item.end_date*1000"
							@change="changeLog($event,item)" />
					</uni-td>
					<uni-td v-if="userInfo.username == 'admin'"><button @click="del(item._id)" class="mini-btn"
							type="warn" size="mini">删除</button></uni-td>
				</uni-tr>
			</uni-table>
			<uni-popup ref="popup" type="center">
				<view class=""
					style="background-color: #fff;min-width: 50%;max-width:80%;border-radius: 10rpx;padding: 20rpx;margin: auto;">
					<view class="" style="text-align: center;font-weight: 400;width: auto;margin-bottom: 20rpx;">
						新增
					</view>
					<uni-forms :modelValue="fromData">
						<uni-forms-item label="过期时间:" :label-width="formLabelWidth">
							<div class="block">
								<uni-datetime-picker :value="fromData.value1*1000" v-model="fromData.value1" type="timestamp"
									placeholder="选择日期时间" >
								</uni-datetime-picker>
							</div>
						</uni-forms-item>
						<uni-forms-item label="用户:" :label-width="formLabelWidth">
							<uni-data-select style="background-color: #fff;" :localdata="userListSelect"
								@change="setUser"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="服务器:" :label-width="formLabelWidth">
							<uni-data-checkbox :multiple="true" multiple v-model="checkedCities"
								:localdata="serviceList" @change="setServerChange"></uni-data-checkbox>
						
						</uni-forms-item>
						<uni-forms-item label="是否立即生效:" :label-width="formLabelWidth">
							<switch checked style="transform:scale(0.7)" @change="switch1Change" />
							是 / 否
						</uni-forms-item>
					</uni-forms>
					<view class="dialog-footer" style="margin: auto;display: flex;padding-bottom: 20rpx;">
						<button @click="ClessPP" type="default" size="mini">取 消</button>
						<button @click="updateData" type="primary" size="mini">确 定</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import dayjs from 'dayjs'
	const db = uniCloud.database();
	import {
		mapState
	} from 'vuex'
	export default {

		data() {
			return {
				tableData: [],
				username: "",
				fromData: {},
				show: false,
				formLabelWidth: '120px',
				value1: undefined,
				serviceList: [],
				checkedCities: [],
				isIndeterminate: false,
				checkAll: false,
				userList: [],
				user: {},
				checkbox1: null,
				userListSelect: [],
				valid:true
			}
		},
		computed: {
			...mapState('user', ['userInfo']),
		},
		created() {
			this.username = this.userInfo.username
			this.getServiceList();
			this.getService();
			this.getuser();
		},
		methods: {
			switch1Change(e){
				console.log(e.detail.value);
				
			},
			// 选择服务器
			setServerChange(e) {
				console.log(e.detail.value);
				// 判断是否全选
				if (this.checkedCities[0] == -1) {
					this.isIndeterminate = true
					this.serviceList.forEach(item => {
						this.checkedCities.push(item.value)
					})
				} else if(this.isIndeterminate){
					this.checkedCities = [];
					this.isIndeterminate = false
				}

			},
			OpenPP() {
				this.$refs.popup.open()
			},
			ClessPP() {
				this.$refs.popup.close()
			},
			changeLog(e, item) {
				console.log('change事件:', dayjs(e).format("YYYY-MM-DD  HH:mm:ss"));
				item.value1 = dayjs(e).format("YYYY-MM-DD  HH:mm:ss")
				this.update(item)
			},
			setUser(val) {
				console.log(val);
				this.user = val
			},
			getuser() {
				db.collection('uni-id-users').where({
					username: db.command.neq('admin')
				}).field('_id,username').get().then((res) => {
					this.userList = res.result.data
					let data = []
					this.userList.forEach(item => {
						data.push({
							value: item._id,
							text: item.username
						})
					})
					this.userListSelect = data
				})
			},
			getService() {

				db.collection('service_url').get().then((res) => {
					this.serviceList.push({
						value: -1,
						text: "全选"
					})
					res.result.data.forEach(item => {
						this.serviceList.push({
							value: item._id,
							text: item.name
						})
					})
					console.log(this.serviceList);

				})
			},
			updateData() {
				// console.log(this.user);
				if (!this.fromData.value1) {
					this.$message.error('请选择过期时间!');
				} else if (!this.user) {
					this.$message.error('请选择用户!');
				} else if (this.checkedCities.length == 0) {
					this.$message.error('请选择至少选择一个服务器!');
				} else {
					this.fromData.end_date = dayjs(this.fromData.value1).unix()
					this.checkedCities.forEach(item => {
						if (item != -1) {
							db.collection('user_services').add({
								service_id: item,
								user_id: this.user,
								end_date: this.fromData.end_date,
								valid: this.valid
							})
						}
					})
					this.show = false
					this.ClessPP()
					this.$message({
						message: '新增成功',
						type: 'success'
					});
					this.getServiceList()
				}
			},
			del(val) {
				this.$confirm('确认删除？')
					.then(_ => {
						db.collection('user_services').where({
							'_id': val
						}).remove().then((res) => {
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.getServiceList()
						})
						done();
					})
					.catch(_ => {});
			},
			update(val) {
				db.collection('user_services').where({
					'_id': val._id
				}).update({
					end_date: dayjs(val.value1).unix()
				}).then((res) => {
					this.getServiceList();
					this.$message({
						message: '修改成功',
						type: 'success'
					});
				})
			},
			setValid(val) {
				console.log(val);
				db.collection('user_services').where({
					'_id': val._id
				}).update({
					'valid': !val.valid
				}).then((res) => {
					this.$message({
						message: '修改成功',
						type: 'success'
					});
				})
			},
			handleClick(val) {
				this.fromData = val
			},
			tableRowClassName({
				row,
				rowIndex
			}) {
				if (rowIndex === 1) {
					return 'warning-row';
				} else if (rowIndex === 3) {
					return 'success-row';
				}
				return '';
			},
			async getServiceList() {
				this.tableData = []
				if (this.userInfo.username != 'admin') {
					const service_url = db.collection('service_url').getTemp()
					const user_services = db.collection('user_services').where({
						'user_id': this.userInfo._id
					}).getTemp()

					const {
						result: res4
					} = await db.collection(user_services, service_url).get()
					res4.data.forEach(res => {
						console.log(res + " res");
						this.tableData.push({
							_id: res._id,
							end_date: res.end_date,
							valid: res.valid,
							user_id: res.user_id,
							service_id: res.service_id[0]._id,
							name: res.service_id[0].name,
							newdate: res.service_id[0].newdate,
							outdate: res.service_id[0].outdate,
							type: res.service_id[0].type,
							url: res.service_id[0].url,
						})
					})
				} else {
					const service_url = db.collection('service_url').getTemp()
					const user_services = db.collection('user_services').getTemp()
					const uni_id_users = db.collection('uni-id-users').field("_id,username").getTemp()
					const result = await db.collection(user_services, service_url, uni_id_users).get()
					const arr4 = [];
					result.result.data.forEach(res => {
						arr4.push({
							_id: res._id,
							end_date: res.end_date,
							valid: res.valid,
							user_id: res.user_id[0]._id,
							username: res.user_id[0].username,
							service_id: res.service_id[0]._id,
							name: res.service_id[0].name,
							newdate: res.service_id[0].newdate,
							outdate: res.service_id[0].outdate,
							type: res.service_id[0].type,
							url: res.service_id[0].url,
							value1: dayjs(res.end_date * 1000).format(
								"YYYY-MM-DD  HH:mm:ss")
						})
					})
					console.log(arr4);
					this.tableData = arr4
				}
			}
		}
	}
</script>

<style>
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

</style>